package com.triplelink.context;

import org.openrdf.repository.RepositoryConnection;
import org.openrdf.repository.RepositoryException;
import org.openrdf.repository.base.RepositoryBase;

import com.triplelink.exception.TripleLinkException;

public class Connector
{
	private final RepositoryBase repositoryBase;
	private RepositoryConnection con;
	
	public Connector (RepositoryBase repositoryBase)
	{
		this.repositoryBase = repositoryBase;
	}
	
	public boolean isConnectionOpen()
	{
		return con != null;
	}
	
	@Override
	protected void finalize() throws Throwable
	{
		super.finalize();
		
		closeConnection();
	}

	public RepositoryConnection getConnection()
	{
		try
		{
			if (con == null)
				con = repositoryBase.getConnection();
		}
		catch (RepositoryException e)
		{
			throw new TripleLinkException(e);
		}
		
		return con;
	}
	
	public void closeConnection()
	{
		close(getConnection());
	}
	
	private void close(RepositoryConnection conn)
	{
		try
		{
			if (conn != null)
			{
				conn.close();
			}
			
		}
		catch (RepositoryException e)
		{
			throw new TripleLinkException(e);
		}
	}

	public RepositoryBase getRepositoryBase() {
		return repositoryBase;
	}
}